//
//  EmoticonsTool.swift
//  MyWeiBo
//
//  Created by mac on 15/3/13.
//  Copyright (c) 2015年 gpr. All rights reserved.
//

import UIKit

class EmoticonsTool: NSObject {
    static var emtionGroups: [EmoticonsGroup]?
    static var emtionMapping: [String: Emoticon]?
    
    class func loadEmotionsGroup() -> [EmoticonsGroup]{
        if emtionGroups != nil { return emtionGroups! }
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil)
        let groupArray = NSArray(contentsOfFile: path!)
        var emotionGroup = [EmoticonsGroup]()
        var map = [String: Emoticon]()
        for dict in groupArray! {
            let group = EmoticonsGroup.objectWithDictionary(dict as! [String : AnyObject]) as! EmoticonsGroup
            emotionGroup.append(group)
            if let subMap = group.emotionsMapping {
                map.merge(subMap)
            }
         }
        emtionGroups = emotionGroup
        emtionMapping = map
        return emotionGroup
    }
    
    class func getEmotionMaping() -> [String: Emoticon] {
        if emtionMapping != nil { return  emtionMapping! }
        loadEmotionsGroup()
        return  emtionMapping!
    }
    
    ///  根据传进的文本转化为一个带表情的字符串
    ///
    ///  :param: text       微博文本
    ///  :param: lineHeight 行高
    ///
    ///  :returns: 带表情的文本
    class func atrributeTextWithString(text: String, lineHeight: CGFloat) -> NSAttributedString {
        // 匹配字符串
        let pattern = "\\[(.*?)\\]"
        let regx = NSRegularExpression(pattern: pattern, options: .CaseInsensitive | .DotMatchesLineSeparators, error: nil)
        let nsText = text as NSString
        let attrStringM = NSMutableAttributedString(string: text)
        let results = regx?.matchesInString(text, options: NSMatchingOptions.allZeros, range: NSMakeRange(0, nsText.length)) as! [NSTextCheckingResult]
        let emoticonMap = getEmotionMaping()
        for var i = results.count - 1; i >= 0; i-- {
            let result = results[i]
            let range = result.rangeAtIndex(0)
            let emoStr = nsText.substringWithRange(range)
            let emticon = emoticonMap[emoStr]
            if emticon == nil { continue }
            let attrString = EmoticonTextAttachment.attributedStringWithEmoticon(emticon!, lineHeight: lineHeight)
            attrStringM.replaceCharactersInRange(range, withAttributedString: attrString)
        }
        return attrStringM as NSAttributedString
    }
}

extension Dictionary {
    ///  将字典合并到当前字典
    mutating func merge<K, V>(dict: [K: V]) {
        for (k, v) in dict {
            self.updateValue(v as! Value, forKey: k as! Key)
        }
    }
}
